#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 10:10:30
# @LastEditTime: 2025-03-14 10:10:35
# @Description: AWS监控主程序
###

import os
import sys
import json
import logging
import configparser
from typing import Dict
from compute.ec2_monitor import EC2Monitor
from compute.eks_monitor import EKSMonitor

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

class AWSMonitorSystem:
    """AWS监控系统"""
    
    def __init__(self, config_file: str = 'config.ini'):
        """初始化监控系统
        
        Args:
            config_file: 配置文件路径
        """
        self.config = self._load_config(config_file)
        self.monitors = self._init_monitors()
        
    def _load_config(self, config_file: str) -> Dict:
        """加载配置文件"""
        if not os.path.exists(config_file):
            logging.error(f"配置文件不存在: {config_file}")
            sys.exit(1)
            
        config = configparser.ConfigParser()
        config.read(config_file)
        
        # 只需要基础配置
        return {
            'access_key': config['aws']['access_key'],
            'secret_key': config['aws']['secret_key'],
            'region': config['aws']['region']
        }
        
    def _init_monitors(self) -> Dict:
        """初始化监控模块"""
        return {
            'ec2': EC2Monitor(self.config),
            'eks': EKSMonitor(self.config)
        }
        
    def check_resource_status(self):
        """检查资源状态"""
        try:
            # 检查EC2状态
            ec2_status = self.monitors['ec2'].monitor_all_instances()
            if ec2_status['abnormal_count'] > 0:
                logging.warning(f"发现{ec2_status['abnormal_count']}个异常EC2实例")
                logging.warning("异常实例详情:")
                for instance in ec2_status['top_abnormal']:
                    logging.warning(
                        f"实例: {instance['name']}({instance['id']}) "
                        f"指标: {instance['metric']} "
                        f"当前值: {instance['value']:.2f}%"
                    )
            else:
                logging.info(
                    f"EC2实例状态正常，共{ec2_status['total_instances']}个实例"
                    f"（运行中：{ec2_status['running_instances']}个）"
                )
                
            # 检查EKS状态
            eks_status = self.monitors['eks'].monitor_all_clusters()
            
            # 检查集群状态
            if eks_status['abnormal_clusters']:
                logging.warning(f"发现{len(eks_status['abnormal_clusters'])}个异常EKS集群")
                logging.warning("异常集群详情:")
                for cluster in eks_status['abnormal_clusters']:
                    if 'status' in cluster:
                        logging.warning(
                            f"集群: {cluster['name']} "
                            f"状态: {cluster['status']}"
                        )
                    else:
                        logging.warning(
                            f"集群: {cluster['name']} "
                            f"指标: {cluster['metric']} "
                            f"当前值: {cluster['value']:.2f}%"
                        )
                        
            # 检查节点组状态
            if eks_status['abnormal_nodegroups']:
                logging.warning(f"发现{len(eks_status['abnormal_nodegroups'])}个异常EKS节点组")
                logging.warning("异常节点组详情:")
                for nodegroup in eks_status['abnormal_nodegroups']:
                    if 'status' in nodegroup:
                        logging.warning(
                            f"集群: {nodegroup['cluster']} "
                            f"节点组: {nodegroup['nodegroup']} "
                            f"状态: {nodegroup['status']}"
                        )
                    else:
                        logging.warning(
                            f"集群: {nodegroup['cluster']} "
                            f"节点组: {nodegroup['nodegroup']} "
                            f"指标: {nodegroup['metric']} "
                            f"当前值: {nodegroup['value']:.2f}%"
                        )
            
            if not eks_status['abnormal_clusters'] and not eks_status['abnormal_nodegroups']:
                logging.info(f"EKS集群状态正常，共{eks_status['total_clusters']}个集群")
                    
        except Exception as e:
            logging.error(f"监控检查失败: {e}")
            return False
            
        return True

def main():
    """主函数"""
    # 获取脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    config_file = os.path.join(script_dir, 'config.ini')
    
    # 初始化监控系统
    monitor_system = AWSMonitorSystem(config_file)
    
    # 运行监控检查
    monitor_system.check_resource_status()

if __name__ == "__main__":
    main()
